<?php

namespace Tbf\Bundle\ConfigBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
use Tbf\Bundle\ConfigBundle\ConfigManager;

/**
 * TbfConfig symfony 扩展
 * 这个组件比较特殊,需要在其他组件之前生成配置
 */
class TbfConfigExtension extends Extension implements PrependExtensionInterface
{
    /**
     * 在其他组件之前生成配置
     * @param ContainerBuilder $container
     */
    public function prepend(ContainerBuilder $container)
    {
        if ($container->hasParameter('tbf_config.config_path')) {
            $config_path = $container->getParameter('tbf_config.config_path');
        } else {
            if ($container->getParameter('kernel.environment')==='test') {
                $config_path = $container->getParameter('kernel.root_dir').'/config/tbf_config_generate_test.yml';
            } else {
                $config_path = $container->getParameter('kernel.root_dir').'/config/tbf_config_generate.yml';
            }
            $container->setParameter('tbf_config.config_path',$config_path);
        }

        $loader = new Loader\YamlFileLoader($container,new FileLocator(dirname($config_path)));
        try {
            $loader->load(basename($config_path));
        } catch (\InvalidArgumentException $e) {
            //如果加载不进来,仅做一个log,其他什么也不做
            $container->getCompiler()->addLogMessage($e->getMessage());
        }

        //确保每一个配置都存在
        $config_manager = new ConfigManager($container,$config_path,new EventDispatcher());
        foreach ($config_manager->getManageParameterList() as $name=>$value) {
            $container->setParameter($name,$value);
        }
    }

    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.xml');
    }
}
